<?php

/******************************************************************************
 *
 *	PROJECT: Flynax Classifieds Software
 *	VERSION: 4.0.1
 *	LISENSE: FL87MPRYOA0R - http://www.flynax.com/license-agreement.html
 *	PRODUCT: Auto Classifieds
 *	DOMAIN: www.siyaradiali.com
 *	FILE: RLFIELDS.CLASS.PHP
 *
 *	This script is a commercial software and any kind of using it must be 
 *	coordinate with Flynax Owners Team and be agree to Flynax License Agreement
 *
 *	This block may not be removed from this file or any other files with out 
 *	permission of Flynax respective owners.
 *
 *	Copyrights Flynax Classifieds Software | 2012
 *	http://www.flynax.com/
 *
 ******************************************************************************/

class rlFields extends reefless
{
	/**
	* @var language class object
	**/
	var $rlLang;
	
	/**
	* @var validator class object
	**/
	var $rlValid;
	
	/**
	* @var configurations class object
	**/
	var $rlConfig;
	
	/**
	* @var administrator controller class object
	**/
	var $rlAdmin;
	
	/**
	* @var actions class object
	**/
	var $rlActions;
	
	/**
	* @var notice class object
	**/
	var $rlNotice;
	
	/**
	* @var new fields ID
	**/
	var $addID;
	
	/**
	* class constructor
	**/
	function rlFields()
	{
		global $rlLang, $rlValid, $rlConfig, $rlAdmin, $rlActions, $rlNotice;
		
		$this -> rlLang   =  & $rlLang;
		$this -> rlValid  =  & $rlValid;
		$this -> rlConfig =  & $rlConfig;
		$this -> rlAdmin =   & $rlAdmin;
		$this -> rlActions = & $rlActions;
		$this -> rlNotice =  & $rlNotice;
	}
	
	/**
	* create new listing field
	*
	* @param string $type - field type
	* @param array $data - new field information
	* @param array $langs - available system languages
	*
	* @return bool
	**/
	function createListingField( $type, $data, $langs )
	{
		$info = array();
		$lang_keys = array();

		// insert field information
		$info = array(
			'Key' => $data['key'],
			'Type' => $type,
			'Required' => $data['required'],
			'Map' => $data['map'],
			'Status' => $data['status']
		);
		
		$info['Add_page'] = empty($data['add_page']) ? '0' : '1';
		$info['Details_page'] = empty($data['details_page']) ? '0' : '1';

		foreach ($langs as $key => $value)
		{
			$lang_keys[] = array(
				'Code' => $langs[$key]['Code'],
				'Module' => 'common',
				'Status' => 'active',
				'Key' => 'listing_fields+name+' . $data['key'],
				'Value' => $data['names'][$langs[$key]['Code']],
			);
			
			if ( !empty($data['description'][$langs[$key]['Code']]) )
			{
				$lang_keys[] = array(
					'Code' => $langs[$key]['Code'],
					'Module' => 'common',
					'Status' => 'active',
					'Key' => 'listing_fields+description+' . $data['key'],
					'Value' => $data['description'][$langs[$key]['Code']],
				);
			}
		}
		
		// generate lang keys and type's additional information
		switch ( $type ){
			case 'text':
				if ( !empty($data['condition']) )
				{
					$info['Condition'] = $data['condition'];
				}
				$info['Values'] = $data['maxlength'] > 255 ? 255 : $data['maxlength'];
				$info['Multilingual'] = $data['multilingual'];
				
				foreach ($langs as $key => $value)
				{
					if ( !empty($data['default'][$langs[$key]['Code']]) )
					{
						$info['Default'] = 1;
						
						$lang_keys[] = array(
							'Code' => $langs[$key]['Code'],
							'Module' => 'common',
							'Status' => 'active',
							'Key' => 'listing_fields+default+' . $data['key'],
							'Value' => $data['default'][$langs[$key]['Code']],
						);
					}
				}

				/* change field typr to MEDIUMTEXT */
				if ( $info['fields']['Multilingual'] )
				{
					$lang_count = count($GLOBALS['languages']);
					if ( ($info['fields']['Values'] + 13) * $lang_count > 255 )
					{
						$alter = "ALTER TABLE `". RL_DBPREFIX ."listings` ADD `{$data['key']}` `{$data['key']}` MEDIUMTEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL";
					}
				}
				/* set default field type/length */
				else
				{
					$alter = "ALTER TABLE `" . RL_DBPREFIX . "listings` ADD `{$data['key']}` VARCHAR( {$data['maxlength']} ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL";
				}
			break;
			
			case 'textarea':
				if ( $data['condition'] )
				{
					$info['Condition'] = $data['condition'];
				}
				
				$info['Values'] = empty($data['maxlength']) ? 500 : $data['maxlength'];
				$info['Multilingual'] = $data['multilingual'];
				
				// alter table field
				$alter = "ALTER TABLE `" . RL_DBPREFIX . "listings` ADD `{$data['key']}` MEDIUMTEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL";
			break;
			
			case 'number':
				$info['Default'] = $data['min'];
				$info['Values'] = $data['max'];
				
				// alter table field
				$alter = "ALTER TABLE `" . RL_DBPREFIX . "listings` ADD `{$data['key']}` DOUBLE NOT NULL";
			break;
			
			case 'date':
				$info['Default'] = $data['mode'];
				
				// alter table field
				$alter = "ALTER TABLE `" . RL_DBPREFIX . "listings` ADD `{$data['key']}` DATE NOT NULL";
				if ( $data['mode'] == 'multi')
				{
					$additional_alter = "ALTER TABLE `" . RL_DBPREFIX . "listings` ADD `{$data['key']}_multi` DATE NOT NULL";
				}
			break;
			
			case 'price':
			case 'unit':
				// alter table field
				$alter = "ALTER TABLE `" . RL_DBPREFIX . "listings` ADD `{$data['key']}` VARCHAR( 100 ) NOT NULL";
			break;
			
			case 'bool':
				$info['Default'] = $data['default'];
				
				// alter table field
				$alter = "ALTER TABLE `" . RL_DBPREFIX . "listings` ADD `{$data['key']}` ENUM( '0', '1' ) DEFAULT '{$data['default']}' NOT NULL";
			break;

			case 'mixed':
				$info['Condition'] = $data['mixed_data_format'];
				if (!$info['Condition'])
				{	
					$info['Default'] = $data['default'] ? $data['default'] : '';
	
					foreach ( $data['items'] as $sKey => $sVal)
					{
						foreach ($langs as $lKey => $lVal)
						{
							$lang_keys[] = array(
								'Code' => $langs[$lKey]['Code'],
								'Module' => 'common',
								'Status' => 'active',
								'Key' => 'listing_fields+name+' . $data['key'] . '_' . $sKey,
								'Value' => $data['items'][$sKey][$langs[$lKey]['Code']],
							);
						}
						// build multivalues field
						$mValues .= $sKey . ',';
					}
					
					$info['Values'] = substr( $mValues, 0, -1 );
				}
				
				// alter table field
				$alter = "ALTER TABLE `" . RL_DBPREFIX . "listings` ADD `{$data['key']}` VARCHAR( 255 ) NOT NULL";
			break;
			
			case 'checkbox':
				$info['Opt1'] = $_POST['show_tils'] ? 1 : 0;
				$info['Opt2'] = (int)$_POST['column_number'];
			case 'select':
			case 'radio':
				$info['Condition'] = $data['data_format'];
				if (!$info['Condition'])
				{	
					$info['Default'] = $data['default'] ? $data['default'] : '';
	
					foreach ( $data['items'] as $sKey => $sVal)
					{
						foreach ($langs as $lKey => $lVal)
						{
							$lang_keys[] = array(
								'Code' => $langs[$lKey]['Code'],
								'Module' => 'common',
								'Status' => 'active',
								'Key' => 'listing_fields+name+' . $data['key'] . '_' . $sKey,
								'Value' => $data['items'][$sKey][$langs[$lKey]['Code']],
							);
						}
						// build multivalues field
						$mValues .= $sKey . ',';
					}
					
					$info['Values'] = substr( $mValues, 0, -1 );
				}
				
				// alter table field
				$alter = "ALTER TABLE `" . RL_DBPREFIX . "listings` ADD `{$data['key']}` VARCHAR( 255 ) NOT NULL";
			break;
			
			case 'image':
				$info['Default'] = $data['resize_type'];
				
				if($data['resize_type'] == 'C')
				{
					$info['Values'] = $data['width'] . '|' . $data['height'];
				}
				elseif ($data['resize_type'] == 'W')
				{
					$info['Values'] = $data['width'];
				}
				elseif ($data['resize_type'] == 'H')
				{
					$info['Values'] = $data['height'];
				}
				
				// alter table field
				$alter = "ALTER TABLE `" . RL_DBPREFIX . "listings` ADD `{$data['key']}` VARCHAR( 255 ) NOT NULL";
			break;
			
			case 'file':
				$info['Default'] = $data['file_type'];

				// alter table field
				$alter = "ALTER TABLE `" . RL_DBPREFIX . "listings` ADD `{$data['key']}` VARCHAR( 255 ) NOT NULL";
			break;
			
			case 'accept':
			
				foreach ($langs as $key => $value)
				{					
					$lang_keys[] = array(
						'Code' => $langs[$key]['Code'],
						'Module' => 'common',
						'Status' => 'active',
						'Key' => 'listing_fields+default+' . $data['key'],
						'Value' => $data['accept'][$langs[$key]['Code']]
					);
				}

				// alter table field
				$alter = "ALTER TABLE `" . RL_DBPREFIX . "listings` ADD `{$data['key']}` ENUM( '0', '1' ) DEFAULT '0' NOT NULL";
			break;
		};

		if ( $this -> query( $alter ) )
		{
			// run additional alter query
			if ( !empty($additional_alter) )
			{
				if ( !$this -> query( $additional_alter ) )
				{
					trigger_error( "Can not create additional listing field (MYSQL ALTER QUERY FAIL)", E_WARNING );
					$GLOBALS['rlDebug'] -> logger("Can not create additional listing field (MYSQL ALTER QUERY FAIL)");
				}
			}

			// insert new fiels information
			$this -> rlActions -> insertOne( $info, 'listing_fields' );
			$this -> addID = mysql_insert_id();

			// insert new fiels language's keys
			$this -> rlActions -> insert( $lang_keys, 'lang_keys' );
			
			return true;
		}
		else 
		{
			trigger_error( "Can not create new listing field (MYSQL ALTER QUERY FAIL)", E_WARNING );
			$GLOBALS['rlDebug'] -> logger("Can not create new listing field (MYSQL ALTER QUERY FAIL)");
		}
		
		return false;
	}
	
	/**
	* edit listing field
	*
	* @param string $type - field type
	* @param array $data - new field information
	* @param array $langs - available system languages
	*
	* @return bool
	**/
	function editListingField( $type, $data, $langs )
	{
		global $config;
		
		$info = array();
		$lang_keys = array();
		$lang_rewrite = true;

		// edit field information
		$info['where'] = array(
			'Key' => $data['key']
		);
		
		$info['fields'] = array(
			'Required' => $data['required'],
			'Map' => $data['map'],
			'Status' => $data['status']
		);
		
		$info['fields']['Add_page'] = empty($data['add_page']) ? '0' : '1';
		$info['fields']['Details_page'] = empty($data['details_page']) ? '0' : '1';

		foreach ($langs as $key => $value)
		{
			if ( $this -> getOne('ID', "`Key` = 'listing_fields+name+{$data['key']}' AND `Code` = '{$langs[$key]['Code']}'", 'lang_keys') )
			{
				// edit names
				$update_phrases = array(
					'fields' => array(
						'Value' => $data['names'][$langs[$key]['Code']]
					),
					'where' => array(
						'Code' => $langs[$key]['Code'],
						'Key' => 'listing_fields+name+' . $data['key']
					)
				);
				
				// update
				$this -> rlActions -> updateOne( $update_phrases, 'lang_keys' );
			}
			else
			{
				// insert names
				$insert_phrases = array(
					'Code' => $langs[$key]['Code'],
					'Module' => 'common',
					'Key' => 'listing_fields+name+' . $data['key'],
					'Value' => $data['names'][$langs[$key]['Code']]
				);
				
				// insert
				$this -> rlActions -> insertOne( $insert_phrases, 'lang_keys' );
			}
		
			$exist_description = $this -> getOne('ID', "`Key` = 'listing_fields+description+{$data['key']}' AND `Code` = '{$langs[$key]['Code']}'", 'lang_keys');	
			if ( $exist_description )
			{
				// update fields description
				$lang_keys_desc['where'] = array(
					'Code' => $langs[$key]['Code'],
					'Key' => 'listing_fields+description+' . $data['key']
				);
				
				$lang_keys_desc['fields'] = array(
					'Value' => $data['description'][$langs[$key]['Code']]
				);
				$this -> rlActions -> updateOne( $lang_keys_desc, 'lang_keys' );
			}
			else
			{
				// insert new description
				if ( !empty($data['description'][$langs[$key]['Code']]) )
				{
					$field_description = array(
						'Code' => $langs[$key]['Code'],
						'Module' => 'common',
						'Status' => 'active',
						'Key' => 'listing_fields+description+' . $data['key'],
						'Value' => $data['description'][$langs[$key]['Code']],
					);
					$this -> rlActions -> insertOne( $field_description, 'lang_keys' );
				}
			}
		}
		
		// generate lang keys and types for additional information
		switch ( $type ){
			case 'text':
				$info['fields']['Condition'] = $data['condition'];
				$info['fields']['Multilingual'] = $data['multilingual'];
				$info['fields']['Values'] = $data['maxlength'] > 255 ? 255 : $data['maxlength'];
				
				if( $data['key'] != 'keyword_search' )
				{
					/* change field typr to MEDIUMTEXT */
					if ( $this -> getOne('Multilingual', "`Key` = '{$data['key']}'", 'listing_fields') != $info['fields']['Multilingual'] && $info['fields']['Multilingual'] )
					{
						$lang_count = count($GLOBALS['languages']);
						if ( ($info['fields']['Values'] + 13) * $lang_count > 255 )
						{
							$additional_alter = "ALTER TABLE `". RL_DBPREFIX ."listings` CHANGE `{$data['key']}` `{$data['key']}` MEDIUMTEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL";
						}
					}
					/* change field typr to VARCHAR */
					elseif ( $this -> getOne('Multilingual', "`Key` = '{$data['key']}'", 'listing_fields') != $info['fields']['Multilingual'] && !$info['fields']['Multilingual'] )
					{
						$additional_alter = "ALTER TABLE `". RL_DBPREFIX ."listings` CHANGE `{$data['key']}` `{$data['key']}` VARCHAR({$info['fields']['Values']}) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL";
						
						/* remove tags from the listings */
						$custom_sql = "UPDATE `". RL_DBPREFIX ."listings` SET `{$data['key']}` = IF (LOCATE('{|/', `{$data['key']}`) > 0, IF (LOCATE('{|{$config['lang']}|}', `{$data['key']}`) > 0, SUBSTRING(`{$data['key']}` FROM LOCATE('{|{$config['lang']}|}', `{$data['key']}`)+6 FOR LOCATE('{|/{$config['lang']}|}', `{$data['key']}`) - LOCATE('{|{$config['lang']}|}', `{$data['key']}`)-6), SUBSTRING(`{$data['key']}` FROM 7 FOR LOCATE('{|/', `{$data['key']}`)-7)), `{$data['key']}`) WHERE `{$data['key']}` IS NOT NULL";
						$this -> query($custom_sql);
					}
					/* set default field type/length */
					else
					{
						$additional_alter = "ALTER TABLE `". RL_DBPREFIX ."listings` CHANGE `{$data['key']}` `{$data['key']}` VARCHAR({$info['fields']['Values']}) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL";
					}
				}
				
				foreach ($langs as $key => $value)
				{
					$info['fields']['Default'] = 1;
					
					$lang_keys[] = array(
						'Code' => $langs[$key]['Code'],
						'Module' => 'common',
						'Status' => 'active',
						'Key' => 'listing_fields+default+' . $data['key'],
						'Value' => $data['default'][$langs[$key]['Code']],
					);
				}

			break;
			
			case 'textarea':
				$info['fields']['Condition'] = $data['condition'];
				$info['fields']['Values'] = $data['maxlength'];
				$info['fields']['Multilingual'] = $data['multilingual'];
				
				if ( $this -> getOne('Multilingual', "`Key` = '{$data['key']}'", 'listing_fields') != $info['fields']['Multilingual'] && !$info['fields']['Multilingual'] )
				{
					/* remove tags from the listings */
					$custom_sql = "UPDATE `". RL_DBPREFIX ."listings` SET `{$data['key']}` = IF (LOCATE('{|{$config['lang']}|}', `{$data['key']}`) > 0, SUBSTRING(`{$data['key']}` FROM LOCATE('{|{$config['lang']}|}', `{$data['key']}`)+6 FOR LOCATE('{|/{$config['lang']}|}', `{$data['key']}`) - LOCATE('{|{$config['lang']}|}', `{$data['key']}`)-6), SUBSTRING(`{$data['key']}` FROM 7 FOR LOCATE('{|/', `{$data['key']}`)-7)) WHERE `{$data['key']}` IS NOT NULL";
					$this -> query($custom_sql);
				}
			break;
			
			case 'number':
				$info['fields']['Default'] = $data['min'];
				$info['fields']['Values'] = $data['max'];
			break;
			
			case 'date':
				$info['fields']['Default'] = $data['mode'];
				
				if ( $data['mode'] == 'multi' )
				{
					$tmp_fieds_list = $this -> getAll("SHOW COLUMNS FROM `" . RL_DBPREFIX . "listings`");
					foreach ($tmp_fieds_list as $fKey => $fVal)
					{
						$fields_list[$tmp_fieds_list[$fKey]['Field']] = $tmp_fieds_list[$fKey];
					}
					unset($tmp_fieds_list);
					
					if ( !array_key_exists($data['key'].'_multi', $fields_list) )
					{
						$additional_alter = "ALTER TABLE `" . RL_DBPREFIX . "listings` ADD `{$data['key']}_multi` DATE NOT NULL AFTER `{$data['key']}`";
					}					
				}
				elseif ( $data['mode'] == 'single' )
				{
					if ( $this -> getRow("SHOW COLUMNS FROM `" . RL_DBPREFIX . "listings` LIKE '{$data['key']}_multi'") )
					{
						$additional_alter = "ALTER TABLE `" . RL_DBPREFIX . "listings` DROP `{$data['key']}_multi`";
					}
				}
			break;
			
			case 'bool':
				$info['fields']['Default'] = $data['default'];
			break;

			case 'mixed':
				$info['fields']['Condition'] = $data['mixed_data_format'];
				if (!$data['data_format'])
				{
					$info['fields']['Default'] = $data['default'] ? $data['default'] : '';
	
					foreach ( $data['items'] as $sKey => $sVal)
					{
						foreach ($langs as $lKey => $lVal)
						{
							$lang_keys[] = array(
								'Code' => $langs[$lKey]['Code'],
								'Module' => 'common',
								'Status' => 'active',
								'Key' => 'listing_fields+name+' . $data['key'] . '_' . $sKey,
								'Value' => $data['items'][$sKey][$langs[$lKey]['Code']],
							);
						}
						// build multivalues field
						$mValues .= $sKey . ',';
					}
					
					$info['fields']['Values'] = substr( $mValues, 0, -1 );
				}
			break;
			
			case 'checkbox':
				$info['fields']['Opt1'] = $_POST['show_tils'] ? '1' : '0';
				$info['fields']['Opt2'] = (int)$_POST['column_number'];
			case 'select':
			case 'radio':
				$info['fields']['Condition'] = $data['data_format'];
				
				if (!$data['data_format'])
				{
					$info['fields']['Default'] = $data['default'] ? $data['default'] : '';
	
					foreach ( $data['items'] as $sKey => $sVal)
					{
						foreach ($langs as $lKey => $lVal)
						{
							$lang_keys[] = array(
								'Code' => $langs[$lKey]['Code'],
								'Module' => 'common',
								'Status' => 'active',
								'Key' => 'listing_fields+name+' . $data['key'] . '_' . $sKey,
								'Value' => $data['items'][$sKey][$langs[$lKey]['Code']],
							);
						}
						// build multivalues field
						$mValues .= $sKey . ',';
					}
					
					$info['fields']['Values'] = substr( $mValues, 0, -1 );
				}
			break;
			
			case 'image':
				$info['fields']['Default'] = $data['resize_type'];
				
				if($data['resize_type'] == 'C')
				{
					$info['fields']['Values'] = $data['width'] . '|' . $data['height'];
				}
				elseif ($data['resize_type'] == 'W')
				{
					$info['fields']['Values'] = $data['width'];
				}
				elseif ($data['resize_type'] == 'H')
				{
					$info['fields']['Values'] = $data['height'];
				}
			break;
			
			case 'file':
				$info['fields']['Default'] = $data['file_type'];
			break;
			
			case 'accept':
				foreach ($langs as $key => $value)
				{
					$lang_keys_accept['where'] = array(
						'Code' => $langs[$key]['Code'],
						'Key' => 'listing_fields+default+' . $data['key']
					);
					
					$lang_keys_accept['fields'] = array(
						'Value' => $data['accept'][$langs[$key]['Code']]
					);
					
					// update
					$this -> rlActions -> updateOne( $lang_keys_accept, 'lang_keys' );
				}
				
				$lang_rewrite = false;
			break;
		};

		if ( !empty($info) )
		{
			// run additional alter query
			if ( !empty($additional_alter) )
			{
				if ( !$this -> query( $additional_alter ) )
				{
					trigger_error( "Can not create additional listing field (MYSQL ALTER QUERY FAIL)", E_WARNING );
					$GLOBALS['rlDebug'] -> logger("Can not create additional listing field (MYSQL ALTER QUERY FAIL)");
				}
			}
			
			// insert new fiels information
			$this -> rlActions -> updateOne( $info, 'listing_fields' );
		}

		if ( !empty($lang_keys) && $lang_rewrite === true )
		{
			// delete languages phrases by current field
			$lSql = "DELETE FROM `" . RL_DBPREFIX . "lang_keys` WHERE (`Key` REGEXP '^listing_fields(.*){$data['key']}_([0-9][a-zA-Z]*)$' OR `Key` = 'listing_fields+default+{$data['key']}') AND `Key` <> 'listing_fields+name+{$data['key']}'";
			$this -> query( $lSql );
			
			// insert new fiels language's keys
			$this -> rlActions -> insert( $lang_keys, 'lang_keys' );
		}
		
		return true;
	}
	
	/**
	* delete listing field
	*
	* @package ajax
	*
	* @param string $key - field key
	*
	**/
	function ajaxDeleteLField( $key = false )
	{
		global $_response, $lang, $rlCache, $rlListingTypes, $rlActions, $allLangs, $type_info, $f_key, $fields;

		// get field info
		$field = $this -> fetch(array('ID', 'Readonly', 'Values'), array('Key' => $key), null, 1, 'listing_fields', 'row');

		if ( !$key || !$field['ID'] )
		{
			trigger_error( "Can not delete listing field, field with requested key does not exist", E_WARNING );
			$GLOBALS['rlDebug'] -> logger("Can not delete listing field, field with requested key does not exist");
			
			return $_response;
		}
		
		if ( $field['Readonly'] )
		{
			$error = str_replace('{field}', $lang['listing_fields+name+'.$key], $lang['field_protected']);
			$_response -> script("printMessage('error', '{$error}')");
			
			return $_response;
		}
		
		// DROP field from the lsitings table
		$sql = "ALTER TABLE `" . RL_DBPREFIX . "listings` DROP `{$key}` ";

		if ( $this -> query( $sql ) )
		{
			$GLOBALS['rlHook'] -> load('apPhpFieldsAjaxDeleteField');

			// delete information from listing_fields table
			$sql = "DELETE FROM `" . RL_DBPREFIX . "listing_fields` WHERE `Key` = '{$key}'";
			$this -> query( $sql );
			
			// delete languages phrases by current field
			$sql = "DELETE FROM `" . RL_DBPREFIX . "lang_keys` WHERE `Key` = 'listing_fields+name+{$key}' OR `Key` = 'listing_fields+default+{$key}' OR `Key` = 'listing_fields+description+{$key}'";
			$this -> query( $sql );
			
			// delete field relations from submit forms
			$field_rel = $this -> fetch( array('ID', 'Fields'), null, "WHERE FIND_IN_SET('{$field['ID']}', `Fields`) > 0", null, 'listing_relations' );
			foreach ($field_rel as $field_item)
			{
				$c_fields = explode( ',', trim( $field_item['Fields'], ',' ) );
				$poss = array_search( $field['ID'], $c_fields);

				unset($c_fields[$poss]);
				
				if (!empty($c_fields))
				{
					$sql = "UPDATE `" . RL_DBPREFIX . "listing_relations` SET `Fields` = '" . implode( ',', $c_fields ) . ",' WHERE `ID` = '{$field_item['ID']}'";
				}
				else
				{
					$sql = "DELETE FROM `" . RL_DBPREFIX . "listing_relations` WHERE `ID` = '{$field_item['ID']}'";
				}
				$this -> query( $sql );
			}
			
			// delete field relations from search forms
			$search_rel = $this -> fetch( array('ID', 'Fields'), null, "WHERE FIND_IN_SET('{$field['ID']}', `Fields`) > 0", null, 'search_forms_relations' );
			foreach ($search_rel as $search_item)
			{
				$c_fields = explode( ',', trim( $search_item['Fields'], ',' ) );
				$poss = array_search( $field['ID'], $c_fields);

				unset($c_fields[$poss]);
				
				if (!empty($c_fields))
				{
					$sql = "UPDATE `" . RL_DBPREFIX . "search_forms_relations` SET `Fields` = '" . implode( ',', $c_fields ) . ",' WHERE `ID` = '{$search_item['ID']}'";
				}
				else
				{
					$sql = "DELETE FROM `" . RL_DBPREFIX . "search_forms_relations` WHERE `ID` = '{$search_item['ID']}'";
				}
				$this -> query( $sql );
			}
			
			// delete field relations from short form
			$sql = "DELETE FROM `" . RL_DBPREFIX . "short_forms` WHERE `Field_ID` = '{$field['ID']}'";
			$this -> query( $sql );
			
			// delete field relations from listing title form
			$sql = "DELETE FROM `" . RL_DBPREFIX . "listing_titles` WHERE `Field_ID` = '{$field['ID']}'";
			$this -> query( $sql );
			
			// delete field relations from featured form
			$sql = "DELETE FROM `" . RL_DBPREFIX . "featured_form` WHERE `Field_ID` = '{$field['ID']}'";
			$this -> query( $sql );

			// delete arrange relations
			/* prepare arrange fields */
			foreach ( $rlListingTypes -> types as $lt )
			{
				if ( $lt['Arrange_field'] )
				{
					$arrange_keys[$lt['Arrange_field']] = $lt['Key'];
				}
			}
			
			if ( isset($arrange_keys[$key]) )
			{
				/* symulate data */
				$type_info = $rlListingTypes -> types[$arrange_keys[$key]];
				$f_key = $arrange_keys[$key];
				$fields[$key]['Values'] = $field['Values'];
				
				// remove all related modules
				if ( $type_info['Arrange_search'] )
				{
					$rlListingTypes -> arrange_search_remove($type_info['Arrange_field']);
				}
				
				if ( $type_info['Arrange_featured'] )
				{
					$rlListingTypes -> arrange_featured_remove($type_info['Arrange_field']);
				}
				
				if ( $type_info['Arrange_stats'] )
				{
					$rlListingTypes -> arrange_statistics_remove($type_info['Arrange_field']);
				}
				
				/* remove arrange data from type */
				$sql = "UPDATE `" . RL_DBPREFIX . "listing_types` SET `Arrange_field` = '', `Arrange_values` = '', `Arrange_search` = '0', `Arrange_featured` = '0', `Arrange_stats` = '0' WHERE `Key` = '{$arrange_keys[$key]}' LIMIT 1";
				$this -> query( $sql );
				
				/* remove data from type globals */
				$rlListingTypes -> types[$arrange_keys[$key]]['Arrange_field'] = '';
				$rlListingTypes -> types[$arrange_keys[$key]]['Arrange_values'] = '';
				$rlListingTypes -> types[$arrange_keys[$key]]['Arrange_search'] = 0;
				$rlListingTypes -> types[$arrange_keys[$key]]['Arrange_featured'] = 0;
				$rlListingTypes -> types[$arrange_keys[$key]]['Arrange_stats'] = 0;
			}
			
			/* update cache */
			$rlCache -> updateSearchForms();
			$rlCache -> updateSearchFields();
			$rlCache -> updateListingStatistics();
			
			$_response -> script("
				listingFieldsGrid.reload();
				printMessage('notice', '{$lang['field_deleted']}');
			");
		}
		
		return $_response;
	}
	
	/**
	* create new register field
	*
	* @param string $type - field type
	* @param array $data - new field information
	* @param array $langs - available system languages
	*
	* @return bool
	**/

	function createRegisterField( $type, $data, $langs )
	{
		$info = array();
		$lang_keys = array();

		// insert field information
		$info = array(
			'Key' => $data['key'],
			'Type' => $type,
			'Required' => $data['required'],
			'Map' => $data['map'],
			'Status' => $data['status']
		);

		foreach ($langs as $key => $value)
		{
			$lang_keys[] = array(
				'Code' => $langs[$key]['Code'],
				'Module' => 'common',
				'Status' => 'active',
				'Key' => 'account_fields+name+' . $data['key'],
				'Value' => $data['names'][$langs[$key]['Code']],
			);
			
			if ( !empty($data['description'][$langs[$key]['Code']]) )
			{
				$lang_keys[] = array(
					'Code' => $langs[$key]['Code'],
					'Module' => 'common',
					'Status' => 'active',
					'Key' => 'account_fields+description+' . $data['key'],
					'Value' => $data['description'][$langs[$key]['Code']],
				);
			}
		}
		
			// generate lang keys and type's additional information
		switch ( $type ){
			case 'text':
				if ( !empty($data['condition']) )
				{
					$info['Condition'] = $data['condition'];
				}
				$info['Values'] = $data['maxlength'] > 255 ? 255 : $data['maxlength'];
				
				foreach ($langs as $key => $value)
				{
					if ( !empty($data['default'][$langs[$key]['Code']]) )
					{
						$info['Default'] = 1;
						
						$lang_keys[] = array(
							'Code' => $langs[$key]['Code'],
							'Module' => 'common',
							'Status' => 'active',
							'Key' => 'account_fields+default+' . $data['key'],
							'Value' => $data['default'][$langs[$key]['Code']],
						);
					}
				}
				
				// alter table field
				$alter = "ALTER TABLE `" . RL_DBPREFIX . "accounts` ADD `{$data['key']}` VARCHAR( {$data['maxlength']} ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL";
			break;
			
			case 'textarea':
				$info['Values'] = empty($data['maxlength']) ? 500 : $data['maxlength'];
				
				// alter table field
				$alter = "ALTER TABLE `" . RL_DBPREFIX . "accounts` ADD `{$data['key']}` MEDIUMTEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL";
			break;
			
			case 'number':
				$info['Default'] = $data['min'];
				$info['Values'] = $data['max'];
				
				// alter table field
				$alter = "ALTER TABLE `" . RL_DBPREFIX . "accounts` ADD `{$data['key']}` DOUBLE NOT NULL";
			break;
			
			case 'date':
				$info['Default'] = $data['mode'];
				
				// alter table field
				$alter = "ALTER TABLE `" . RL_DBPREFIX . "accounts` ADD `{$data['key']}` DATE NOT NULL";
				if ( $data['mode'] == 'multi')
				{
					$additional_alter = "ALTER TABLE `" . RL_DBPREFIX . "accounts` ADD `{$data['key']}_multi` DATE NOT NULL";
				}
			break;
			
			case 'price':
			case 'unit':
				// alter table field
				$alter = "ALTER TABLE `" . RL_DBPREFIX . "accounts` ADD `{$data['key']}` VARCHAR( 100 ) NOT NULL";
			break;
			
			case 'bool':
				$info['Default'] = $data['default'];
				
				// alter table field
				$alter = "ALTER TABLE `" . RL_DBPREFIX . "accounts` ADD `{$data['key']}` ENUM( '0', '1' ) DEFAULT '{$data['default']}' NOT NULL";
			break;

			case 'mixed':
				$info['Condition'] = $data['mixed_data_format'];
				if (!$info['Condition'])
				{	
					$info['Default'] = $data['default'] ? $data['default'] : '';
	
					foreach ( $data['items'] as $sKey => $sVal)
					{
						foreach ($langs as $lKey => $lVal)
						{
							$lang_keys[] = array(
								'Code' => $langs[$lKey]['Code'],
								'Module' => 'common',
								'Status' => 'active',
								'Key' => 'account_fields+name+' . $data['key'] . '_' . $sKey,
								'Value' => $data['items'][$sKey][$langs[$lKey]['Code']],
							);
						}
						// build multivalues field
						$mValues .= $sKey . ',';
					}
					
					$info['Values'] = substr( $mValues, 0, -1 );
				}
				
				// alter table field
				$alter = "ALTER TABLE `" . RL_DBPREFIX . "accounts` ADD `{$data['key']}` VARCHAR( 255 ) NOT NULL";
			break;
			
			case 'select':
			case 'radio':
			case 'checkbox':
				$info['Condition'] = $data['data_format'];
				if (!$info['Condition'])
				{	
					$info['Default'] = $data['default'] ? $data['default'] : '';
	
					foreach ( $data['items'] as $sKey => $sVal)
					{
						foreach ($langs as $lKey => $lVal)
						{
							$lang_keys[] = array(
								'Code' => $langs[$lKey]['Code'],
								'Module' => 'common',
								'Status' => 'active',
								'Key' => 'account_fields+name+' . $data['key'] . '_' . $sKey,
								'Value' => $data['items'][$sKey][$langs[$lKey]['Code']],
							);
						}
						// build multivalues field
						$mValues .= $sKey . ',';
					}
					
					$info['Values'] = substr( $mValues, 0, -1 );
				}
				
				// alter table field
				$alter = "ALTER TABLE `" . RL_DBPREFIX . "accounts` ADD `{$data['key']}` VARCHAR( 255 ) NOT NULL";
			break;
			
			case 'image':
				$info['Default'] = $data['resize_type'];
				
				if($data['resize_type'] == 'C')
				{
					$info['Values'] = $data['width'] . '|' . $data['height'];
				}
				elseif ($data['resize_type'] == 'W')
				{
					$info['Values'] = $data['width'];
				}
				elseif ($data['resize_type'] == 'H')
				{
					$info['Values'] = $data['height'];
				}
				
				// alter table field
				$alter = "ALTER TABLE `" . RL_DBPREFIX . "accounts` ADD `{$data['key']}` VARCHAR( 255 ) NOT NULL";
			break;
			
			case 'file':
				$info['Default'] = $data['file_type'];

				// alter table field
				$alter = "ALTER TABLE `" . RL_DBPREFIX . "accounts` ADD `{$data['key']}` VARCHAR( 255 ) NOT NULL";
			break;
			
			case 'accept':
			
				foreach ($langs as $key => $value)
				{					
					$lang_keys[] = array(
						'Code' => $langs[$key]['Code'],
						'Module' => 'common',
						'Status' => 'active',
						'Key' => 'account_fields+default+' . $data['key'],
						'Value' => $data['accept'][$langs[$key]['Code']]
					);
				}

				// alter table field
				$alter = "ALTER TABLE `" . RL_DBPREFIX . "accounts` ADD `{$data['key']}` ENUM( '0', '1' ) DEFAULT '0' NOT NULL";
			break;
		};

		if ( $this -> query( $alter ) )
		{
			// run additional alter query
			if ( !empty($additional_alter) )
			{
				if ( !$this -> query( $additional_alter ) )
				{
					trigger_error( "Can not create additional account field (MYSQL ALTER QUERY FAIL)", E_WARNING );
					$GLOBALS['rlDebug'] -> logger("Can not create additional account field (MYSQL ALTER QUERY FAIL)");
				}
			}

			// insert new fiels information
			$this -> rlActions -> insertOne( $info, 'account_fields' );
			$this -> addID = mysql_insert_id();

			// insert new fiels language's keys
			$this -> rlActions -> insert( $lang_keys, 'lang_keys' );
			
			return true;
		}
		else 
		{
			trigger_error( "Can not create new account field (MYSQL ALTER QUERY FAIL)", E_WARNING );
			$GLOBALS['rlDebug'] -> logger("Can not create new account field (MYSQL ALTER QUERY FAIL)");
		}
		
		return false;
	}
	
	/**
	* edit register field
	*
	* @param string $type - field type
	* @param array $data - new field information
	* @param array $langs - available system languages
	*
	* @return bool
	**/
	function editRegisterField( $type, $data, $langs )
	{
		$info = array();
		$lang_keys = array();
		$lang_rewrite = true;

		// edit field information
		$info['where'] = array(
			'Key' => $data['key']
		);
		
		$info['fields'] = array(
			'Map' => $data['map'],
			'Status' => $data['status']
		);

		foreach ($langs as $key => $value)
		{
			if ( $this -> getOne('ID', "`Key` = 'account_fields+name+{$data['key']}' AND `Code` = '{$langs[$key]['Code']}'", 'lang_keys') )
			{
				// edit names
				$update_names = array(
					'fields' => array(
						'Value' => $data['names'][$langs[$key]['Code']]
					),
					'where' => array(
						'Code' => $langs[$key]['Code'],
						'Key' => 'account_fields+name+' . $data['key']
					)
				);
				
				// update
				$this -> rlActions -> updateOne( $update_names, 'lang_keys' );
			}
			else
			{
				// insert names
				$insert_phrases = array(
					'Code' => $langs[$key]['Code'],
					'Module' => 'common',
					'Key' => 'account_fields+name+' . $data['key'],
					'Value' => $data['names'][$langs[$key]['Code']]
				);
				
				// insert
				$this -> rlActions -> insertOne( $insert_phrases, 'lang_keys' );
			}
			
			$exist_description = $this -> getOne('ID', "`Key` = 'account_fields+description+{$data['key']}' AND `Code` = '{$langs[$key]['Code']}'", 'lang_keys');	
			if ( $exist_description )
			{
				// update fields description
				$lang_keys_desc['where'] = array(
					'Code' => $langs[$key]['Code'],
					'Key' => 'account_fields+description+' . $data['key']
				);
				
				$lang_keys_desc['fields'] = array(
					'Value' => $data['description'][$langs[$key]['Code']]
				);
				$this -> rlActions -> updateOne( $lang_keys_desc, 'lang_keys' );
			}
			else
			{
				// insert new description
				if ( !empty($data['description'][$langs[$key]['Code']]) )
				{
					$field_description = array(
						'Code' => $langs[$key]['Code'],
						'Module' => 'common',
						'Status' => 'active',
						'Key' => 'account_fields+description+' . $data['key'],
						'Value' => $data['description'][$langs[$key]['Code']],
					);
					$this -> rlActions -> insertOne( $field_description, 'lang_keys' );
				}
			}
		}
		
		// generate lang keys and types for additional information
		switch ( $type ){
			case 'text':
				$info['fields']['Condition'] = $data['condition'];
				$info['fields']['Values'] = $data['maxlength'];
				
				$additional_alter = "ALTER TABLE `". RL_DBPREFIX ."accounts` CHANGE `{$data['key']}` `{$data['key']}` VARCHAR({$info['fields']['Values']}) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL";
				
				foreach ($langs as $key => $value)
				{
					//if ( !empty($data['default'][$langs[$key]['Code']]) )
					//{
						$info['fields']['Default'] = 1;
						
						$lang_keys[] = array(
							'Code' => $langs[$key]['Code'],
							'Module' => 'common',
							'Status' => 'active',
							'Key' => 'account_fields+default+' . $data['key'],
							'Value' => $data['default'][$langs[$key]['Code']],
						);
					/*}
					else 
					{
						$info['fields']['Default'] = 0;
					}*/
				}

			break;
			
			case 'textarea':
				$info['fields']['Values'] = $data['maxlength'];
			break;
			
			case 'number':
				$info['fields']['Default'] = $data['min'];
				$info['fields']['Values'] = $data['max'];
			break;
			
			case 'date':
				$info['fields']['Default'] = $data['mode'];
			break;
			
			case 'bool':
				$info['fields']['Default'] = $data['default'];
			break;
			
			case 'select':
				$info['fields']['Condition'] = $data['data_format'];
				
				if (!$data['data_format'])
				{
					$info['fields']['Default'] = $data['default'] ? $data['default'] : '';

					foreach ( $data['items'] as $sKey => $sVal)
					{
						foreach ($langs as $lKey => $lVal)
						{
							$lang_keys[] = array(
								'Code' => $langs[$lKey]['Code'],
								'Module' => 'common',
								'Status' => 'active',
								'Key' => 'account_fields+name+' . $data['key'] . '_' . $sKey,
								'Value' => $data['items'][$sKey][$langs[$lKey]['Code']],
							);
						}
						// build multivalues field
						$mValues .= $sKey . ',';
					}
					
					$info['fields']['Values'] = substr( $mValues, 0, -1 );
				}
			break;
			
			case 'mixed':
				$info['fields']['Condition'] = $data['mixed_data_format'];
			case 'radio':
			case 'checkbox':
				if (!$data['data_format'])
				{
					$info['fields']['Default'] = $data['default'] ? $data['default'] : '';

					foreach ( $data['items'] as $sKey => $sVal)
					{
						foreach ($langs as $lKey => $lVal)
						{
							$lang_keys[] = array(
								'Code' => $langs[$lKey]['Code'],
								'Module' => 'common',
								'Status' => 'active',
								'Key' => 'account_fields+name+' . $data['key'] . '_' . $sKey,
								'Value' => $data['items'][$sKey][$langs[$lKey]['Code']],
							);
						}
						// build multivalues field
						$mValues .= $sKey . ',';
					}
					
					$info['fields']['Values'] = substr( $mValues, 0, -1 );
				}
			break;
			
			case 'image':
				$info['fields']['Default'] = $data['resize_type'];
				
				if($data['resize_type'] == 'C')
				{
					$info['fields']['Values'] = $data['width'] . '|' . $data['height'];
				}
				elseif ($data['resize_type'] == 'W')
				{
					$info['fields']['Values'] = $data['width'];
				}
				elseif ($data['resize_type'] == 'H')
				{
					$info['fields']['Values'] = $data['height'];
				}
			break;
			
			case 'file':
				$info['fields']['Default'] = $data['file_type'];
			break;
			
			case 'accept':
				foreach ($langs as $key => $value)
				{
					$lang_keys_accept['where'] = array(
						'Code' => $langs[$key]['Code'],
						'Key' => 'account_fields+default+' . $data['key']
					);
					
					$lang_keys_accept['fields'] = array(
						'Value' => $data['accept'][$langs[$key]['Code']]
					);
					
					// update
					$this -> rlActions -> updateOne( $lang_keys_accept, 'lang_keys' );
				}
				
				$lang_rewrite = false;
			break;
		};
		
		if ( !empty($info) )
		{
			// run additional alter query
			if ( !empty($additional_alter) )
			{
				if ( !$this -> query( $additional_alter ) )
				{
					trigger_error( "Can not edit additional account field (MYSQL ALTER QUERY FAIL)", E_WARNING );
					$GLOBALS['rlDebug'] -> logger("Can not edit additional account field (MYSQL ALTER QUERY FAIL)");
				}
			}
			
			// insert new fiels information
			$this -> rlActions -> updateOne( $info, 'account_fields' );
		}

		if ( !empty($lang_keys) && $lang_rewrite === true )
		{
			// delete languages phrases by current field
			$lSql = "DELETE FROM `" . RL_DBPREFIX . "lang_keys` WHERE (`Key` REGEXP '^account_fields(.*){$data['key']}_([0-9][a-zA-Z]*)$' OR `Key` =  'account_fields+default+{$data['key']}') AND `Key` <> 'account_fields+name+{$data['key']}'";
			$this -> query( $lSql );
			
			// insert new fiels language's keys
			$this -> rlActions -> insert( $lang_keys, 'lang_keys' );
		}
		
		return true;
	}
	
	/**
	* delete account field
	*
	* @package ajax
	*
	* @param string $key - field key
	*
	**/
	function ajaxDeleteAField( $key )
	{
		global $_response, $lang;

		// DROP field from the lsitings table
		$sql = "ALTER TABLE `" . RL_DBPREFIX . "accounts` DROP `{$key}` ";
		
		if( $this -> query($sql) )
		{
			$id = $this -> getOne('ID', "`Key` = '{$key}'", 'account_fields');
			
			// delete information from listing_fields table
			$sql = "DELETE FROM `" . RL_DBPREFIX . "account_fields` WHERE `Key` = '{$key}' LIMIT 1";
			$this -> query( $sql );
		
			// delete languages phrases by current field
			$sql = "DELETE FROM `" . RL_DBPREFIX . "lang_keys` WHERE `Key` LIKE 'account_fields+name+{$key}%' OR `Key` LIKE 'account_fields+default+{$key}'";
			
			/* remove field relations */
			$sql = "DELETE FROM `" . RL_DBPREFIX . "account_search_relations` WHERE `Field_ID` = '{$id}'";
			$this -> query( $sql );
			
			$sql = "DELETE FROM `" . RL_DBPREFIX . "account_short_form` WHERE `Field_ID` = '{$id}'";
			$this -> query( $sql );
			
			$sql = "DELETE FROM `" . RL_DBPREFIX . "account_submit_form` WHERE `Field_ID` = '{$id}'";
			$this -> query( $sql );
			
			$_response -> script("
				accountFieldsGrid.reload();
				printMessage('notice', '{$lang['field_deleted']}');
			");
		}
		
		return $_response;
	}
}
